
// WinHomeClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "WinHomeClient.h"
#include "WinHomeClientDlg.h"
#include "WMP/CWMPHost.h"
#include "../ServerDataHelper/ServerData.h"
#include <direct.h>
#include "Gdiplus.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define WM_DOTASKINMESSAGELOOP WM_USER+3000

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CWinHomeClientDlg dialog




CWinHomeClientDlg::CWinHomeClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWinHomeClientDlg::IDD, pParent)
	, m_URL(_T(""))
	, m_ServerIP(0)
	, m_strFilePlay(_T(""))
	, m_DownloadHelper(this)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_MediaPlayerWindow = NULL;
	m_nPage = PAGE_INIT;
}

void CWinHomeClientDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_URL);
	DDX_IPAddress(pDX, IDC_IPADDRESS1, m_ServerIP);
	DDX_Control(pDX, IDC_IPADDRESS1, m_ServerIPCtrl);
	DDX_Text(pDX, IDC_EDIT2, m_strFilePlay);
	DDX_Control(pDX, IDC_LIST_SERVER, m_SharedFolderListCtrl);
	DDX_Control(pDX, IDC_LIST_MEDIA, m_MediaListCtrl);
}

BEGIN_MESSAGE_MAP(CWinHomeClientDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_PLAY, &CWinHomeClientDlg::OnBnClickedButtonPlay)
	ON_BN_CLICKED(IDC_BUTTON_REFRESH, &CWinHomeClientDlg::OnBnClickedButtonRefresh)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_SERVER, &CWinHomeClientDlg::OnNMDblclkListServer)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_MEDIA, &CWinHomeClientDlg::OnLvnItemchangedListMedia)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_MEDIA, &CWinHomeClientDlg::OnNMDblclkListMedia)
	ON_MESSAGE(WM_DOTASKINMESSAGELOOP,&CWinHomeClientDlg::DoTaskInMessageLoop)
END_MESSAGE_MAP()


// CWinHomeClientDlg message handlers

BOOL CWinHomeClientDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	m_Config.LoadConfig();
	m_ServerIP = m_Config.m_IPAddress;
	m_strFilePlay = m_Config.m_SharedFolder.c_str();
	UpdateData(FALSE);

	m_RootListImageList.Create(48,48,ILC_COLOR32,1,0);
	m_RootListImageList.Add(AfxGetApp()->LoadIcon(IDI_ICON_FOLDER));
	//m_SharedFolderListCtrl.SetImageList(&m_RootListImageList,LVSIL_SMALL);
	//m_SharedFolderListCtrl.SetImageList(&m_RootListImageList,LVSIL_STATE);
	m_SharedFolderListCtrl.SetImageList(&m_RootListImageList,LVSIL_NORMAL);

	m_MediaListImageList.Create(48,48,ILC_COLOR32,1,0);
	m_MediaListCtrl.SetImageList(&m_MediaListImageList,LVSIL_NORMAL);

	CRect rt;
	m_SharedFolderListCtrl.GetWindowRect(&rt);
	ScreenToClient(&rt);
	m_MediaListCtrl.MoveWindow(&rt);
	SetPage(PAGE_INIT);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CWinHomeClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWinHomeClientDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWinHomeClientDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

CComModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()

wstring CWinHomeClientDlg::GetBaseURL()
{
	m_Config.m_IPAddress = m_ServerIP;
	m_Config.m_SharedFolder = m_strFilePlay;
	m_Config.SaveConfig();

	BYTE A1,A2,A3,A4;
	m_ServerIPCtrl.GetAddress(A1,A2,A3,A4);
	wstring URLPlay = _T("http://");
	TCHAR szNum[100] = {0};
	_stprintf(szNum,_T("%d"),A1);
	URLPlay += szNum;
	URLPlay += _T(".");

	_stprintf(szNum,_T("%d"),A2);
	URLPlay += szNum;
	URLPlay += _T(".");

	_stprintf(szNum,_T("%d"),A3);
	URLPlay += szNum;
	URLPlay += _T(".");

	_stprintf(szNum,_T("%d"),A4);
	URLPlay += szNum;
	URLPlay += _T(":8080/");

	return URLPlay;

}
void CWinHomeClientDlg::OnBnClickedButtonPlay()
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	wstring URLPlay = GetBaseURL();
	URLPlay += m_strFilePlay;

	CoInitialize(0);
    _Module.Init( ObjectMap, AfxGetInstanceHandle(), &LIBID_ATLLib );

	::InitCommonControls();

	if (m_MediaPlayerWindow == NULL)
	{
		m_MediaPlayerWindow = new CWMPHost();
		m_MediaPlayerWindow->GetWndClassInfo().m_wc.hIcon = NULL;
		CRect rcPos;
		GetClientRect(&rcPos);
		m_MediaPlayerWindow->Create(GetSafeHwnd(), rcPos, _T("WMP Host Container"), 0, 0, (HMENU)0);
		m_MediaPlayerWindow->ShowWindow(SW_SHOWNORMAL);
	}

	if (m_MediaPlayerWindow->m_spWMPPlayer)
		m_MediaPlayerWindow->m_spWMPPlayer->put_URL(CComBSTR(URLPlay.c_str()));
}

void CWinHomeClientDlg::OnBnClickedButtonRefresh()
{
	// TODO: Add your control notification handler code here
	wstring URLPlay = GetBaseURL();
	URLPlay += _T("Root");
	wstring dbPath = m_Config.m_ConfigPath;
	dbPath += _T("ClientReceive");
	_wmkdir(dbPath.c_str());
	dbPath += _T("\\ServerData.db");

	tDownloadTask *task = new tDownloadTask(URLPlay,PAGE_SHAREFOLDER);
	m_Tasks[task->m_URL] = task;
	
	m_DownloadHelper.DownloadFile(URLPlay,dbPath,_T(""));

	SetPage(PAGE_SHAREFOLDER);
}
void CWinHomeClientDlg::DoTask(tDownloadTask* task)
{
	if (task == NULL)
		return;
	switch(task->m_TaskType)
	{
	case PAGE_SHAREFOLDER:
		RefreshServerFolders();
		break;
	case PAGE_MEDIA:
		{
			TCHAR* Path = (TCHAR*)task->m_TaskParam;
			if (Path)
			{
				ShowMediaFolder((wstring)Path);
			
				free(Path);
			}
		}
		break;
	case TASK_REFRESH_THUMB:
		{
			SendMessage(WM_DOTASKINMESSAGELOOP,(WPARAM)task,0);
		}
		break;
	}
	
}
LRESULT CWinHomeClientDlg::DoTaskInMessageLoop(WPARAM wParam,LPARAM lParam)
{
	tDownloadTask* task = (tDownloadTask*)wParam;
	if (task == NULL)
		return 0;
	switch(task->m_TaskType)
	{
		case TASK_REFRESH_THUMB:
		{
			SERVERDATA_MEDIA* pMedia = (SERVERDATA_MEDIA*)task->m_TaskParam;
			if (pMedia)
			{
				UpdateMediaThumb(pMedia);
				delete pMedia;
			}
		}
		break;
	}
	return 0;
}
void CWinHomeClientDlg::NotifyEnd(wstring URL)
{
	DoTask(m_Tasks[URL]);

	return;
}
bool CWinHomeClientDlg::IsExist(wstring strFolder)
{
	int Count = m_SharedFolderListCtrl.GetItemCount();
	for( int i=0;i<Count;i++)
	{
		CString ItemText =m_SharedFolderListCtrl.GetItemText(i,0);
		if (ItemText.CompareNoCase(strFolder.c_str()) == 0)
			return true;
	}
	return false;
}
bool CWinHomeClientDlg::IsExistMedia(wstring strFolder)
{
	int Count = m_MediaListCtrl.GetItemCount();
	for( int i=0;i<Count;i++)
	{
		CString ItemText =m_MediaListCtrl.GetItemText(i,0);
		if (ItemText.CompareNoCase(strFolder.c_str()) == 0)
			return true;
	}
	return false;
}

void CWinHomeClientDlg::RefreshServerFolders()
{
	wstring dbPath = m_Config.m_ConfigPath;
	dbPath += _T("ClientReceive\\ServerData.db");

	InitServerData((TCHAR*)dbPath.c_str());

	int Count = 0;
	GetShareFoldersCount(&Count);

	if (Count > 0)
		m_SharedFolderListCtrl.EnableWindow();

	for (int i=0;i<Count;i++)
	{
		SERVERDATA_SHAREDFOLDER FolderData;
		GetShareFolder(i,&FolderData);
		if (!IsExist((LPCTSTR)FolderData.szPath))
			m_SharedFolderListCtrl.InsertItem(m_SharedFolderListCtrl.GetItemCount(),FolderData.szPath,0);
	}
}

void CWinHomeClientDlg::OnNMDblclkListServer(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	
	//Show Media list,hide shared folder list
	m_MediaListCtrl.DeleteAllItems();

	SetPage(PAGE_MEDIA);
	wstring URLPlay = GetBaseURL();
	URLPlay += _T("Content");
	wstring requestFile = m_SharedFolderListCtrl.GetItemText(pNMItemActivate->iItem,0);

	wstring dbPath = m_Config.m_ConfigPath;
	dbPath += _T("ClientReceive");
	_wmkdir(dbPath.c_str());
	dbPath += _T("\\ThumbData.db");

	tDownloadTask *task = new tDownloadTask(URLPlay,PAGE_MEDIA);
	task->m_TaskParam = (void*)_tcsdup(requestFile.c_str());
	m_Tasks[task->m_URL] = task;

	m_DownloadHelper.DownloadFile(URLPlay,dbPath,requestFile);

	SetPage(PAGE_MEDIA);
	*pResult = 0;
}

void CWinHomeClientDlg::OnLvnItemchangedListMedia(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;
}

void CWinHomeClientDlg::OnNMDblclkListMedia(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;
}
void CWinHomeClientDlg::ShowMediaFolder(wstring Folder)
{
	wstring dbPath = m_Config.m_ConfigPath;
	dbPath += _T("ClientReceive\\");
	_wmkdir(dbPath.c_str());
	dbPath += _T("ThumbData.db");

	InitServerData((TCHAR*)dbPath.c_str());
	int Count = 0;
	GetShareFolderMediasCount((TCHAR*)Folder.c_str(),&Count);
	if (Count == 0)
		return;
	for (int i = 0;i<Count;i++)
	{
		SERVERDATA_MEDIA MediaData;
		GetShareFolderMediasInfo((TCHAR*)Folder.c_str(),i,&MediaData);
		if (!IsExistMedia((LPCTSTR)MediaData.szPath))
		{
			m_MediaListCtrl.InsertItem(m_MediaListCtrl.GetItemCount(),MediaData.szPath,0);

			wstring URLPlay = GetBaseURL();
			URLPlay += _T("Thumbnail");
			wstring Task = URLPlay;
			Task += _T("?");
			Task += MediaData.szThumbPath;

			dbPath = m_Config.m_ConfigPath;
			dbPath += _T("ClientReceive\\");
			dbPath += MediaData.id;

			tDownloadTask* task = new tDownloadTask(URLPlay,TASK_REFRESH_THUMB);
			SERVERDATA_MEDIA* dupMedia = new SERVERDATA_MEDIA();
			*dupMedia = MediaData;
			task->m_TaskParam = (void*)dupMedia;
			m_Tasks[Task] = task;

			m_DownloadHelper.DownloadFile(Task,dbPath,_T(""));
		}


	}
}

void CWinHomeClientDlg::UpdateMediaThumb(SERVERDATA_MEDIA* pMedia)
{
	if (pMedia == NULL)
		return;
	wstring dbPath = m_Config.m_ConfigPath;
	dbPath += _T("ClientReceive\\");
	dbPath += pMedia->id;

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	CComBSTR bstrFile(dbPath.c_str()); 
	//Gdiplus::Image* im = Gdiplus::Image::FromFile(bstrFile); 
	Gdiplus::Bitmap* bp = Gdiplus::Bitmap::FromFile(bstrFile); 
	if (bp == NULL)
		return;

	HBITMAP hIcon = NULL;
	bp->GetHBITMAP(NULL, &hIcon);
	if (hIcon == NULL)
		return;
	CBitmap bmp;
	bmp.Attach(hIcon);
	int nIcon = m_MediaListImageList.Add(&bmp,COLORREF(0));

	int Count = m_MediaListCtrl.GetItemCount();
	for( int i=0;i<Count;i++)
	{
		CString ItemText =m_MediaListCtrl.GetItemText(i,0);
		if (ItemText.CompareNoCase(pMedia->szPath) == 0)
		{
			m_MediaListCtrl.SetItem(i,0,LVIF_IMAGE,NULL,Count,NULL,NULL,LVIF_PARAM);
			return;
		}
	}	

}